package service

import (
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: CreateUserMsg
//@description: 创建UserMsg记录
//@param: userMsg model.UserMsg
//@return: err error

func CreateUserMsg(userMsg model.UserMsg) (err error) {
	err = global.GVA_DB.Create(&userMsg).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteUserMsg
//@description: 删除UserMsg记录
//@param: userMsg model.UserMsg
//@return: err error

func DeleteUserMsg(userMsg model.UserMsg) (err error) {
	err = global.GVA_DB.Delete(&userMsg).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteUserMsgByIds
//@description: 批量删除UserMsg记录
//@param: ids request.IdsReq
//@return: err error

func DeleteUserMsgByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]model.UserMsg{},"id in ?",ids.Ids).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: UpdateUserMsg
//@description: 更新UserMsg记录
//@param: userMsg *model.UserMsg
//@return: err error

func UpdateUserMsg(userMsg model.UserMsg) (err error) {
	err = global.GVA_DB.Save(&userMsg).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetUserMsg
//@description: 根据id获取UserMsg记录
//@param: id uint
//@return: err error, userMsg model.UserMsg

func GetUserMsg(id uint) (err error, userMsg model.UserMsg) {
	err = global.GVA_DB.Where("id = ?", id).First(&userMsg).Error
	return
}

func GetUserMsgWithPhoneAndCode(phone string ,code int)(err error, userMsg model.UserMsg) {
	err = global.GVA_DB.Where(`phone=? and msg=?`,phone,code).Last(&userMsg).Error
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetUserMsgInfoList
//@description: 分页获取UserMsg记录
//@param: info request.UserMsgSearch
//@return: err error, list interface{}, total int64

func GetUserMsgInfoList(info request.UserMsgSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&model.UserMsg{})
    var userMsgs []model.UserMsg
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.Phone != "" {
        db = db.Where("`phone` = ?",info.Phone)
    }
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&userMsgs).Error
	return err, userMsgs, total
}